<template>
  <field-wrapper
    :activate="activate"
    :field="field"
    :control-flag="controlFlag"
    :hidden-title="hiddenTitle"
    class="field-input"
    @click="emitClick"
    @action="handleAction">

    <div
      v-if="fieldItem"
      class="box">

      <draggable
        v-if="fieldItem.formType === 'detail_table'"
        class="draggable-view"
        :class="[`is-${fieldItem.formType}`, {'is-dragging': dragging}]"
        :list="fieldItem.fieldExtendList"
        :options="dragListConfig"
        @add="dragAdded">
        <div
          v-if="isEmpty"
          class="empty-box">
          <div class="empty-box-title">可拖拽添加多个字段</div>
          <div class="empty-box-desc">（不支持明细中添加明细字段）</div>
        </div>

        <div
          v-if="dragging"
          class="empty-box">
          <div class="empty-box-title">明细表格放入该区域添加</div>
          <div class="empty-box-desc">（不支持明细中添加明细字段）</div>
        </div>

        <wk-field
          v-else
          class="wk-field is-bg-white"
          :item="fieldItem"
          :field-from="fieldFrom"
        >
          <template slot-scope="">
            <el-input :value="field.defaultValue == 'string' ? field.defaultValue : ''" />
          </template>
        </wk-field>
      </draggable>

      <wk-field
        v-else
        class="wk-field"
        :item="fieldItem"
        :field-from="fieldFrom"
      >
        <template slot-scope="">
          <el-input :value="field.defaultValue == 'string' ? field.defaultValue : ''" />
        </template>
      </wk-field>
    </div>

  </field-wrapper>
</template>

<script>
import FieldWrapper from './FieldWrapper'
import WkField from '@/components/NewCom/WkForm/WkField.vue'
import draggable from 'vuedraggable'

import mixins from './mixins'
import { isArray, isEmpty } from '@/utils/types'
import { objDeepCopy } from '@/utils'

export default {
  name: 'FieldItem',
  components: {
    draggable,
    FieldWrapper,
    WkField
  },
  mixins: [mixins],
  data() {
    return {
      fieldItem: null,
      fieldFrom: {},

      dragListConfig: {
        delay: 50,
        group: {
          name: 'childList',
          put: ['libList'],
          pull: false
        },
        sort: false,
        forceFallback: true,
        fallbackClass: 'draggingStyle',
        filter: '.empty-box'
      },
      selectedPoint: [null, null]
    }
  },
  computed: {
    isEmpty() {
      return isEmpty(this.field.fieldExtendList) && ['detail_table'].includes(this.field.formType)
    },

    // 隐藏标题
    hiddenTitle() {
      return ['field_group', 'desc_text'].includes(this.field.formType)
    }
  },

  watch: {
    field: {
      handler() {
        this.initFieldItem()
        this.initFieldValue()
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /**
     * @description:
     * @return {*}
     */
    initFieldItem() {
      const copyField = objDeepCopy(this.field)
      const defaultItem = {
        field: 'value',
        ...copyField
      }

      const { formType } = defaultItem
      if (['user', 'structure'].includes(formType)) {
        defaultItem.radio = copyField.isMulti === 0
      } else if (['detail_table'].includes(formType)) {
        const { fieldExtendList = [] } = defaultItem
        fieldExtendList.forEach((subField, subFieldIndex) => {
          subField.field = `value${subFieldIndex}`
        })
        defaultItem.fieldList = [fieldExtendList]
      }
      this.fieldItem = defaultItem
    },

    /**
     * @description: 初始化value值
     * @return {*}
     */
    initFieldValue() {
      const fieldFrom = {}
      fieldFrom[this.fieldItem.field] = this.getFieldValue(this.fieldItem)
      this.fieldFrom = fieldFrom
    },

    /**
     * @description: 获取字段值
     * @param {*} fieldItem
     * @return {*}
     */
    getFieldValue(fieldItem) {
      const { defaultValue, formType } = fieldItem
      let value = defaultValue
      if (['number', 'floatnumber', 'percent'].includes(formType)) {
        if (defaultValue === '' || defaultValue === null) {
          value = undefined // 防止出现0
        }
      } else if (['user', 'structure'].includes(formType)) {
        const { isMulti } = fieldItem
        if (isMulti === 1) {
          if (isArray(defaultValue)) {
            value = defaultValue
          } else if (typeof defaultValue === 'string') {
            value = defaultValue ? defaultValue.split(',') : []
          } else {
            value = []
          }
        }
      } else if (['file'].includes(formType)) {
        value = isArray(defaultValue) ? defaultValue : []
      } else if (['detail_table'].includes(formType)) {
        const { fieldExtendList = [] } = fieldItem
        const tableValue = {}
        fieldExtendList.forEach(subField => {
          tableValue[subField.field] = this.getFieldValue(subField)
        })
        value = [tableValue]
      }
      return value
    },

    /**
     * 拖拽派发新增事件
     * @param evt
     */
    dragAdded(evt) {
      this.$emit('child-drag-add', this.point, evt)
      this.$nextTick(() => {
        this.selectedPoint = [evt.newIndex, 0]
      })
    }
  }
}
</script>

  <style scoped lang="scss">
  .box {
    width: 100%;

    // height: 32px;
    // padding: 0 10px;
    font-size: 14px;

    // background: white;
    // border: $--border-medium;
    // border-radius: $--border-radius-base;

    .empty-box {
      width: 100%;
      padding: 25px 0;
      text-align: center;

      .empty-box-title {
        color: $--color-text-primary;
      }

      .empty-box-desc {
        margin-top: 5px;
        font-size: 12px;
        color: $--color-text-placeholder;
      }
    }

    ::v-deep .wk-field {
      pointer-events: none;

      * {
        pointer-events: none;
      }

      &.is-bg-white {
        background-color: $--color-white;
      }
    }

    .draggable-view {
      &.is-detail_table {
        min-height: 85px;

        &.is-dragging {
          background-color: $--color-b50;
          border-radius: $--border-radius-base;

          &:hover {
            .empty-box {
              display: none;
            }
          }
        }
      }
    }
  }
  </style>

